package com.hongdezhi.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public class C3P0Utils {
	
	public static DataSource ds = null;
	//每一个线程都拥有自己独立的实例变量副本，而不会和其它线程的副本冲突
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	// 初始化C3P0数据源
	static {
		// 使用c3p0-config.xml配置文件中的named-config节点中name属性的值
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		ds = cpds;
	}
	public static DataSource getDataSource(){
		return ds;
	}
	
	public static Connection getConnection() {
		Connection conn = tl.get();
		try {
			
			if (conn == null) {
				conn = ds.getConnection();
				tl.set(conn);
			}
					
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;

	}

	public static void release(Connection conn) {
		
		if (conn != null) {
			try {
				tl.remove();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
	}

	public static void release(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {

				e.printStackTrace();
			}

		}

	}
}
